/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.util;

import me.panpf.sketch.util.Utils;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.miscservices.wallpaper.WallpaperController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import static ohos.miscservices.wallpaper.WallpaperController.WALLPAPER_SYSTEM;

/**
 * ApplyWallpaperAsyncTask
 */
public class ApplyWallpaperAsyncTask {
    private Context context;
    private File imageFile;
    private TaskDispatcher taskDispatcher;

    public ApplyWallpaperAsyncTask(Context context, File imageFile) {
        this.context = context;
        this.imageFile = imageFile;
    }

    private boolean doBackground() {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(imageFile);
            WallpaperController.getInstance(context).setWallpaper(inputStream, WALLPAPER_SYSTEM);
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * onPostExecute
     * @param b1
     */
    protected void onPostExecute(boolean b1) {
        Utils.toast(context, b1 ? "设置壁纸成功" : "设置壁纸失败");
    }

    /**
     * execute
     */
    public void execute() {
        if (taskDispatcher == null) {
            taskDispatcher = context.createParallelTaskDispatcher("save", TaskPriority.DEFAULT);
        }

        taskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                boolean b1 = doBackground();
                context.getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        onPostExecute(b1);
                    }
                });
            }
        });
    }
}
